import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { useStaticState, useTRState } from '#/utils/trHooks';
import { useThemeChange } from '@/hooks';
import { useDebounceFn } from 'ahooks';
import { getEChartsOption, setTableData } from './helper';
import * as echarts from 'echarts';
import emitter from '#/utils/events';
import styles from './index.less';
import _ from 'lodash';

const TjEcharts = forwardRef((props = {}, ref) => {
  const {
    optionDatas = {},
    onLegendChange = () => {},

    option = {},
    legend = [],
  } = props;

  const { legendBottom = 38 } = optionDatas;
  const { theme } = useThemeChange();

  const [state, setState] = useTRState({
    legend: [],
  });
  const staticState = useStaticState({
    chartIns: null,
    selectedLegend: {},
  });
  const echartsRef = useRef(null);

  const onHandleResize = useDebounceFn(
    () => {
      staticState.chartIns?.resize();
    },
    { wait: 500 },
  );

  const legendChange = (obj = {}) => {
    staticState.selectedLegend[obj.name] = !staticState.selectedLegend[obj.name];
    onLegendChange?.({
      name: obj?.name || '',
      selected: _.clone(staticState.selectedLegend || {}),
      type: 'legendselectchanged',
    });
  };

  const setOptionFun = () => {
    staticState.chartIns.setOption(
      {
        ...getEChartsOption(optionDatas),
        ...(option || {}),
      },
      true,
    );
  };

  useImperativeHandle(ref, () => ({
    onHandleResize,
  }));

  // 初始化图表、监听页面尺寸、图例触发等
  useEffect(() => {
    staticState.chartIns = echarts.init(echartsRef.current);

    staticState.chartIns.on('legendselectchanged', (obj) => {
      obj.selected && onLegendChange?.(obj);
    });

    setOptionFun();
    window.addEventListener('resize', onHandleResize.run);
    emitter.addListener('onChangeMnue', onHandleResize.run);
    return () => {
      window.removeEventListener('resize', onHandleResize.run);
      emitter.removeListener('onChangeMnue', onHandleResize.run);

      staticState.chartIns?.off('legendselectchanged');
      staticState.chartIns.dispose();
      staticState.chartIns = null;
    };
  }, []);

  // 切换主题、图表数据发生改变
  useEffect(() => {
    if (!staticState.chartIns) return;
    setOptionFun();
  }, [JSON.stringify(option), theme]);

  // 自定义图例数据发生改变
  useEffect(() => {
    legend.forEach((v) => {
      staticState.selectedLegend[v.name] = true;
    });
    setState({
      legend,
    });
  }, [JSON.stringify(legend)]);

  return (
    <div className={styles.echarts_container} ref={ref}>
      <div className={styles.echarts_container_canvas} ref={echartsRef} />
      {state.legend?.length ? (
        <div className={styles.echarts_container_legend} style={{ bottom: `${legendBottom}px` }}>
          {state.legend.map((lVal, lInd) => {
            return (
              <div
                key={lVal.name || lInd}
                className={styles.ecl_slide}
                onClick={() => legendChange(lVal)}
              >
                <div className={styles.ecl_slide_icon} />
                <div className={styles.ecl_slide_text}>{lVal.name || '-'}</div>
              </div>
            );
          })}
        </div>
      ) : null}
    </div>
  );
});

export default React.memo(TjEcharts);
